<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>野外生存创造MUD</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: "Microsoft YaHei", sans-serif;
        }

        body {
            background-color: #f0f0f0;
            color: #333;
            line-height: 1.6;
            padding: 20px;
        }

        .game-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .game-header {
            background-color: #2c3e50;
            color: white;
            padding: 10px 20px;
            border-radius: 5px;
            text-align: center;
        }

        .game-content {
            display: flex;
            gap: 20px;
            height: 70vh;
        }

        .game-sidebar {
            width: 250px;
            background-color: #ecf0f1;
            border-radius: 5px;
            padding: 10px;
            overflow-y: auto;
        }

        .game-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .game-output {
            background-color: #fff;
            border-radius: 5px;
            padding: 50px 10px 50px 10px;
            flex: 1;
            overflow-y: auto;
            border: 1px solid #ddd;
        }

        .game-input-container {
            display: flex;
            gap: 10px;
        }

        .game-input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .game-button {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .game-button:hover {
            background-color: #2980b9;
        }

        .panel {
            display: none;
            background-color: white;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 10px;
        }

        .panel.active {
            display: block;
        }

        .panel-title {
            font-size: 1.2em;
            margin-bottom: 10px;
            color: #2c3e50;
        }

        .menu-item {
            padding: 8px 10px;
            cursor: pointer;
            transition: background-color 0.3s;
            border-radius: 3px;
        }

        .menu-item:hover {
            background-color: #ddd;
        }

        .menu-item.active {
            background-color: #3498db;
            color: white;
        }

        .status-bar {
            display: flex;
            gap: 15px;
            background-color: #34495e;
            color: white;
            padding: 10px;
            border-radius: 5px;
        }

        .status-item {
            flex: 1;
            text-align: center;
        }

        .progress-bar {
            background-color: #ecf0f1;
            height: 10px;
            border-radius: 5px;
            margin-top: 5px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background-color: #2ecc71;
            width: 0%;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: #f2f2f2;
        }

        .inventory-item {
            display: flex;
            align-items: center;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }

        .inventory-item:hover {
            background-color: #f5f5f5;
        }

        .item-icon {
            width: 30px;
            height: 30px;
            background-color: #95a5a6;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
            border-radius: 3px;
        }

        .item-name {
            flex: 1;
        }

        .item-actions {
            display: flex;
            gap: 5px;
        }

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal-content {
            background-color: white;
            margin: 10% auto;
            padding: 20px;
            width: 80%;
            max-width: 600px;
            border-radius: 5px;
        }

        .close {
            float: right;
            cursor: pointer;
            font-size: 1.5em;
        }

        .character-creation {
            max-width: 500px;
            margin: 0 auto;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <div class="game-header">
            <h1>野外生存创造MUD</h1>
        </div>

        <div id="character-creation" class="modal">
            <div class="modal-content">
                <span class="close" id="close-character-creation">×</span>
                <h2>创建角色</h2>
                <div class="character-creation">
                    <div class="form-group">
                        <label for="character-name">角色名称</label>
                        <input type="text" id="character-name" placeholder="输入角色名称">
                    </div>
                    <div class="form-group">
                        <label for="character-gender">性别</label>
                        <select id="character-gender">
                            <option value="male">男</option>
                            <option value="female">女</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="character-class">职业</label>
                        <select id="character-class">
                            <option value="hunter">猎人</option>
                            <option value="gatherer">采集者</option>
                            <option value="builder">建造者</option>
                        </select>
                    </div>
                    <button class="game-button" id="create-character">创建角色</button>
                </div>
            </div>
        </div>

        <div class="status-bar">
            <div class="status-item">
                <div>生命值: <span id="health-value">100</span>/<span id="health-max">100</span></div>
                <div class="progress-bar">
                    <div class="progress-fill" id="health-bar" style="width: 100%;"></div>
                </div>
            </div>
            <div class="status-item">
                <div>饥饿度: <span id="hunger-value">100</span>/<span id="hunger-max">100</span></div>
                <div class="progress-bar">
                    <div class="progress-fill" id="hunger-bar" style="width: 100%;"></div>
                </div>
            </div>
            <div class="status-item">
                <div>精力: <span id="energy-value">100</span>/<span id="energy-max">100</span></div>
                <div class="progress-bar">
                    <div class="progress-fill" id="energy-bar" style="width: 100%;"></div>
                </div>
            </div>
        </div>

        <div class="game-content">
            <div class="game-sidebar">
                <div class="menu-item active" data-panel="character">角色信息</div>
                <div class="menu-item" data-panel="inventory">物品栏</div>
                <div class="menu-item" data-panel="crafting">合成</div>
                <div class="menu-item" data-panel="building">建造</div>
                <div class="menu-item" data-panel="tasks">任务</div>
                <div class="menu-item" data-panel="map">地图</div>
                <div class="menu-item" data-panel="settings">设置</div>
                <div class="menu-item" data-panel="creator">创造者</div>
            </div>

            <div class="game-main">
                <div class="game-panels">
                    <div id="character-panel" class="panel active">
                        <h3 class="panel-title">角色信息</h3>
                        <div id="character-info">
                            <p>名称: <span id="char-name">-</span></p>
                            <p>性别: <span id="char-gender">-</span></p>
                            <p>职业: <span id="char-class">-</span></p>
                            <p>等级: <span id="char-level">1</span></p>
                            <p>经验: <span id="char-exp">0</span>/<span id="char-next-exp">100</span></p>
                            <h4>属性</h4>
                            <table id="char-attributes">
                                <tr>
                                    <td>力量</td>
                                    <td id="attr-strength">10</td>
                                </tr>
                                <tr>
                                    <td>敏捷</td>
                                    <td id="attr-agility">10</td>
                                </tr>
                                <tr>
                                    <td>智力</td>
                                    <td id="attr-intelligence">10</td>
                                </tr>
                                <tr>
                                    <td>耐力</td>
                                    <td id="attr-endurance">10</td>
                                </tr>
                            </table>
                            <h4>技能</h4>
                            <table id="char-skills">
                                <tr>
                                    <td>采集</td>
                                    <td id="skill-gathering">1</td>
                                </tr>
                                <tr>
                                    <td>建造</td>
                                    <td id="skill-building">1</td>
                                </tr>
                                <tr>
                                    <td>战斗</td>
                                    <td id="skill-combat">1</td>
                                </tr>
                                <tr>
                                    <td>合成</td>
                                    <td id="skill-crafting">1</td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <div id="inventory-panel" class="panel">
                        <h3 class="panel-title">物品栏</h3>
                        <div id="inventory-list"></div>
                    </div>

                    <div id="crafting-panel" class="panel">
                        <h3 class="panel-title">合成</h3>
                        <div id="recipe-list"></div>
                    </div>

                    <div id="building-panel" class="panel">
                        <h3 class="panel-title">建造</h3>
                        <div id="building-list"></div>
                    </div>

                    <div id="tasks-panel" class="panel">
                        <h3 class="panel-title">任务</h3>
                        <div id="task-list"></div>
                    </div>

                    <div id="map-panel" class="panel">
                        <h3 class="panel-title">地图</h3>
                        <div id="map-display">
                            <div id="current-location"></div>
                            <div id="available-locations"></div>
                        </div>
                    </div>

                    <div id="settings-panel" class="panel">
                        <h3 class="panel-title">设置</h3>
                        <button class="game-button" id="save-game">保存游戏</button>
                        <button class="game-button" id="load-game">加载游戏</button>
                        <button class="game-button" id="new-game">新游戏</button>
                    </div>

                    <div id="creator-panel" class="panel">
                        <h3 class="panel-title">创造者模式</h3>
                        <div id="creator-tools">
                            <p>创造者模式允许您编辑游戏世界和规则。</p>
                            <div class="form-group">
                                <label for="creator-command">命令</label>
                                <input type="text" id="creator-command" placeholder="输入创造者命令">
                            </div>
                            <button class="game-button" id="execute-command">执行</button>
                        </div>
                    </div>
                </div>

                <div class="game-output" id="game-log"></div>

                <div class="game-input-container">
                    <input type="text" class="game-input" id="game-input" placeholder="输入命令...">
                    <button class="game-button" id="submit-command">提交</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // ECS架构 - 实体组件系统
        class ECS {
            constructor() {
                this.entities = new Map();
                this.components = {};
                this.systems = [];
                this.nextEntityId = 1;
            }

            createEntity() {
                const id = this.nextEntityId++;
                this.entities.set(id, new Set());
                return id;
            }

            removeEntity(entityId) {
                if (this.entities.has(entityId)) {
                    const componentTypes = this.entities.get(entityId);
                    for (const type of componentTypes) {
                        if (this.components[type]) {
                            delete this.components[type][entityId];
                        }
                    }
                    this.entities.delete(entityId);
                }
            }

            addComponent(entityId, component) {
                if (!this.entities.has(entityId)) return;
                
                const type = component.constructor.name;
                if (!this.components[type]) {
                    this.components[type] = {};
                }
                this.components[type][entityId] = component;
                this.entities.get(entityId).add(type);
                return component;
            }

            removeComponent(entityId, componentType) {
                if (this.entities.has(entityId) && this.components[componentType]) {
                    delete this.components[componentType][entityId];
                    this.entities.get(entityId).delete(componentType);
                }
            }

            getComponent(entityId, componentType) {
                if (this.components[componentType]) {
                    return this.components[componentType][entityId];
                }
                return null;
            }

            addSystem(system) {
                system.ecs = this;
                this.systems.push(system);
            }

            update(deltaTime) {
                for (const system of this.systems) {
                    system.update(deltaTime);
                }
            }
        }

        // 组件定义
        class NameComponent {
            constructor(name) {
                this.name = name;
            }
        }

        class PositionComponent {
            constructor(x, y, location) {
                this.x = x;
                this.y = y;
                this.location = location;
            }
        }

        class HealthComponent {
            constructor(max) {
                this.max = max;
                this.current = max;
            }
        }

        class HungerComponent {
            constructor(max) {
                this.max = max;
                this.current = max;
                this.rate = 0.5; // 每分钟减少的饥饿度
            }
        }

        class EnergyComponent {
            constructor(max) {
                this.max = max;
                this.current = max;
                this.rate = 0.2; // 每分钟减少的精力
            }
        }

        class InventoryComponent {
            constructor(capacity) {
                this.capacity = capacity;
                this.items = {};
            }

            addItem(itemId, amount) {
                if (!this.items[itemId]) {
                    this.items[itemId] = 0;
                }
                this.items[itemId] += amount;
                return this.items[itemId];
            }

            removeItem(itemId, amount) {
                if (!this.items[itemId] || this.items[itemId] < amount) {
                    return false;
                }
                this.items[itemId] -= amount;
                if (this.items[itemId] <= 0) {
                    delete this.items[itemId];
                }
                return true;
            }

            hasItem(itemId, amount) {
                return this.items[itemId] && this.items[itemId] >= amount;
            }
        }

        class AttributesComponent {
            constructor(strength, agility, intelligence, endurance) {
                this.strength = strength;
                this.agility = agility;
                this.intelligence = intelligence;
                this.endurance = endurance;
            }
        }

        class SkillsComponent {
            constructor() {
                this.gathering = 1;
                this.building = 1;
                this.combat = 1;
                this.crafting = 1;
            }
        }

        class LevelComponent {
            constructor() {
                this.level = 1;
                this.experience = 0;
                this.nextLevelExp = 100;
            }

            addExperience(amount) {
                this.experience += amount;
                if (this.experience >= this.nextLevelExp) {
                    this.levelUp();
                    return true;
                }
                return false;
            }

            levelUp() {
                this.level++;
                this.experience -= this.nextLevelExp;
                this.nextLevelExp = Math.floor(this.nextLevelExp * 1.5);
                return this.level;
            }
        }

        class PlayerComponent {
            constructor(gender, characterClass) {
                this.gender = gender;
                this.characterClass = characterClass;
            }
        }

        class ResourceComponent {
            constructor(type, amount) {
                this.type = type;
                this.amount = amount;
                this.respawnTime = 0;
            }
        }

        class ItemComponent {
            constructor(type, value, usable, equippable) {
                this.type = type;
                this.value = value;
                this.usable = usable;
                this.equippable = equippable;
            }
        }

        class NPCComponent {
            constructor(type, friendly) {
                this.type = type;
                this.friendly = friendly;
                this.dialog = [];
            }
        }

        class TaskComponent {
            constructor(title, description, reward) {
                this.title = title;
                this.description = description;
                this.reward = reward;
                this.completed = false;
                this.requirements = [];
            }
        }

        class CombatComponent {
            constructor(attack, defense) {
                this.attack = attack;
                this.defense = defense;
            }
        }

        class BuildingComponent {
            constructor(type, resources) {
                this.type = type;
                this.resources = resources;
                this.completed = false;
            }
        }

        // 系统定义
        class System {
            constructor() {
                this.ecs = null;
            }

            update(deltaTime) {
                // 基类方法，由子类重写
            }
        }

        class ResourceSystem extends System {
            update(deltaTime) {
                if (!this.ecs.components['ResourceComponent']) return;
                
                for (const [entityId, resource] of Object.entries(this.ecs.components['ResourceComponent'])) {
                    if (resource.amount <= 0 && resource.respawnTime > 0) {
                        resource.respawnTime -= deltaTime;
                        if (resource.respawnTime <= 0) {
                            // 资源重生
                            switch (resource.type) {
                                case 'wood':
                                    resource.amount = Math.floor(Math.random() * 5) + 5;
                                    break;
                                case 'stone':
                                    resource.amount = Math.floor(Math.random() * 3) + 3;
                                    break;
                                case 'herb':
                                    resource.amount = Math.floor(Math.random() * 2) + 1;
                                    break;
                                case 'animal':
                                    resource.amount = 1;
                                    break;
                            }
                            gameLog(`${this.ecs.getComponent(entityId, 'NameComponent').name}重新生成了。`);
                        }
                    }
                }
            }
        }

        class HealthSystem extends System {
            update(deltaTime) {
                if (!this.ecs.components['HealthComponent']) return;
                
                for (const [entityId, health] of Object.entries(this.ecs.components['HealthComponent'])) {
                    if (health.current <= 0) {
                        const nameComponent = this.ecs.getComponent(entityId, 'NameComponent');
                        if (nameComponent) {
                            if (this.ecs.getComponent(entityId, 'PlayerComponent')) {
                                gameLog(`你已经死亡！`);
                                // 处理玩家死亡
                                health.current = health.max * 0.5;
                                const hunger = this.ecs.getComponent(entityId, 'HungerComponent');
                                const energy = this.ecs.getComponent(entityId, 'EnergyComponent');
                                if (hunger) hunger.current = hunger.max * 0.5;
                                if (energy) energy.current = energy.max * 0.5;
                                updateStatusBars();
                                gameLog(`你已经复活，但失去了一些生命、饥饿度和精力。`);
                            } else {
                                gameLog(`${nameComponent.name}死亡了。`);
                                // 处理NPC或动物死亡
                                if (this.ecs.getComponent(entityId, 'NPCComponent')) {
                                    // NPC死亡处理
                                } else {
                                    // 掉落资源
                                    const resourceType = this.ecs.getComponent(entityId, 'ResourceComponent')?.type;
                                    if (resourceType === 'animal') {
                                        const playerEntity = getPlayerEntity();
                                        const inventory = this.ecs.getComponent(playerEntity, 'InventoryComponent');
                                        inventory.addItem('meat', Math.floor(Math.random() * 2) + 1);
                                        inventory.addItem('hide', Math.floor(Math.random() * 2) + 1);
                                        gameLog(`你获得了肉和皮革。`);
                                        updateInventory();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        class HungerSystem extends System {
            update(deltaTime) {
                if (!this.ecs.components['HungerComponent']) return;
                
                for (const [entityId, hunger] of Object.entries(this.ecs.components['HungerComponent'])) {
                    if (this.ecs.getComponent(entityId, 'PlayerComponent')) {
                        hunger.current -= hunger.rate * deltaTime;
                        if (hunger.current < 0) hunger.current = 0;
                        
                        // 如果饥饿度为0，开始减少生命
                        if (hunger.current <= 0) {
                            const health = this.ecs.getComponent(entityId, 'HealthComponent');
                            if (health) {
                                health.current -= 1 * deltaTime;
                                if (health.current < 0) health.current = 0;
                            }
                        }
                        
                        updateStatusBars();
                    }
                }
            }
        }

        class EnergySystem extends System {
            update(deltaTime) {
                if (!this.ecs.components['EnergyComponent']) return;
                
                for (const [entityId, energy] of Object.entries(this.ecs.components['EnergyComponent'])) {
                    if (this.ecs.getComponent(entityId, 'PlayerComponent')) {
                        energy.current -= energy.rate * deltaTime;
                        if (energy.current < 0) energy.current = 0;
                        
                        // 如果精力为0，动作效率降低
                        updateStatusBars();
                    }
                }
            }
        }

        // 游戏状态管理
        class GameState {
            constructor() {
                this.ecs = new ECS();
                this.player = null;
                this.currentLocation = null;
                this.time = 0;
                this.gameSpeed = 1; // 游戏时间流逝速度
                this.lastUpdate = Date.now();
                this.gameRunning = false;
                this.creatorMode = false;
            }

            init() {
                // 初始化系统
                this.ecs.addSystem(new ResourceSystem());
                this.ecs.addSystem(new HealthSystem());
                this.ecs.addSystem(new HungerSystem());
                this.ecs.addSystem(new EnergySystem());
                
                // 初始化游戏世界
                this.initWorld();
                
                // 设置游戏循环
                this.startGameLoop();
            }

            initWorld() {
                // 创建位置
                this.createLocation('camp', '营地', '你的基本营地，可以休息和合成物品。');
                this.createLocation('forest', '森林', '这里有丰富的木材和野生动物。');
                this.createLocation('mountain', '山脉', '这里可以采集石头和矿物。');
                this.createLocation('river', '河流', '这里可以捕鱼和取水。');
                this.createLocation('plain', '平原', '这里适合种植和放牧。');
                
                                // 在各位置创建资源
                                this.createResource('forest', 'tree', '大树', 'wood', 10);
                this.createResource('forest', 'bush', '灌木丛', 'herb', 5);
                this.createResource('forest', 'deer', '鹿', 'animal', 1);
                this.createResource('forest', 'rabbit', '兔子', 'animal', 1);
                
                this.createResource('mountain', 'rock', '岩石', 'stone', 8);
                this.createResource('mountain', 'ore', '矿石', 'ore', 5);
                this.createResource('mountain', 'crystal', '水晶', 'crystal', 2);
                
                this.createResource('river', 'fish', '鱼群', 'fish', 5);
                this.createResource('river', 'reed', '芦苇', 'reed', 7);
                
                this.createResource('plain', 'grass', '草地', 'grass', 15);
                this.createResource('plain', 'fruit', '野果', 'fruit', 6);
                
                // 创建NPC
                this.createNPC('camp', 'elder', '村长', '村庄的长者，知识渊博。', true);
                this.createNPC('forest', 'hunter', '猎人', '一个有经验的猎人，可以教你狩猎技巧。', true);
                this.createNPC('mountain', 'miner', '矿工', '精通采矿技术的工人。', true);
                this.createNPC('forest', 'wolf', '狼', '危险的野兽，会攻击人类。', false);
                
                // 创建任务
                this.createTask('survival_basics', '生存基础', '收集5个木材和3个石头来建造一个基本的庇护所。', 
                                {'exp': 50, 'items': {'tool_basic': 1}},
                                {'wood': 5, 'stone': 3});
                
                this.createTask('first_hunt', '第一次狩猎', '成功猎杀一只动物并获取肉。', 
                                {'exp': 80, 'skill': {'combat': 1}},
                                {'meat': 1});
                
                // 创建配方
                this.createRecipe('tool_basic', '基础工具', {'wood': 3, 'stone': 2}, 'tools');
                this.createRecipe('weapon_spear', '长矛', {'wood': 5, 'stone': 3}, 'weapons');
                this.createRecipe('cooked_meat', '烤肉', {'meat': 1, 'wood': 1}, 'food');
                this.createRecipe('medicine_basic', '基础药物', {'herb': 3}, 'medicine');
                
                // 创建建筑
                this.createBuilding('shelter', '简易庇护所', {'wood': 10, 'stone': 5});
                this.createBuilding('fireplace', '火堆', {'wood': 5, 'stone': 8});
                this.createBuilding('workbench', '工作台', {'wood': 15, 'stone': 10});
                this.createBuilding('storage', '储物箱', {'wood': 20});
                
                this.currentLocation = 'camp';
            }

            createLocation(id, name, description) {
                const locationEntity = this.ecs.createEntity();
                this.ecs.addComponent(locationEntity, new NameComponent(name));
                const locationData = {
                    id: id,
                    description: description,
                    connected: []
                };
                
                // 设置位置连接关系
                switch(id) {
                    case 'camp':
                        locationData.connected = ['forest', 'river'];
                        break;
                    case 'forest':
                        locationData.connected = ['camp', 'mountain', 'plain'];
                        break;
                    case 'mountain':
                        locationData.connected = ['forest'];
                        break;
                    case 'river':
                        locationData.connected = ['camp', 'plain'];
                        break;
                    case 'plain':
                        locationData.connected = ['forest', 'river'];
                        break;
                }
                
                this.ecs.addComponent(locationEntity, {
                    constructor: {name: 'LocationComponent'},
                    ...locationData
                });
                
                return locationEntity;
            }

            createResource(locationId, id, name, type, amount) {
                const resourceEntity = this.ecs.createEntity();
                this.ecs.addComponent(resourceEntity, new NameComponent(name));
                this.ecs.addComponent(resourceEntity, new PositionComponent(0, 0, locationId));
                this.ecs.addComponent(resourceEntity, new ResourceComponent(type, amount));
                
                return resourceEntity;
            }

            createNPC(locationId, id, name, description, friendly) {
                const npcEntity = this.ecs.createEntity();
                this.ecs.addComponent(npcEntity, new NameComponent(name));
                this.ecs.addComponent(npcEntity, new PositionComponent(0, 0, locationId));
                const npc = new NPCComponent(id, friendly);
                npc.description = description;
                
                if (friendly) {
                    this.ecs.addComponent(npcEntity, new HealthComponent(100));
                    
                    // 添加对话
                    switch(id) {
                        case 'elder':
                            npc.dialog = [
                                {text: "欢迎来到我们的营地，旅行者。这里是你的新家。", responses: [
                                    {text: "谢谢您的欢迎。我需要了解一些基本的生存知识。", next: 1},
                                    {text: "我想知道这个世界有什么危险。", next: 2}
                                ]},
                                {text: "首先，你需要收集资源来制作工具和建造庇护所。在森林里可以找到木材，在山上可以找到石头。", responses: [
                                    {text: "我明白了，谢谢您的建议。", next: -1}
                                ]},
                                {text: "森林里有野兽，山上有险恶的地形，河流中有急流。做好准备再冒险。", responses: [
                                    {text: "我会小心的，谢谢提醒。", next: -1}
                                ]}
                            ];
                            break;
                        case 'hunter':
                            npc.dialog = [
                                {text: "嘿，新来的？想学习狩猎技巧吗？", responses: [
                                    {text: "是的，我想学习如何狩猎。", next: 1},
                                    {text: "现在不需要，谢谢。", next: -1}
                                ]},
                                {text: "狩猎首先需要一把像样的武器，比如长矛。然后要学会跟踪动物的足迹。", responses: [
                                    {text: "我该如何制作长矛？", next: 2},
                                    {text: "谢谢指导，我先去尝试一下。", next: -1}
                                ]},
                                {text: "你需要5个木材和3个石头，在工作台上就能制作长矛了。", responses: [
                                    {text: "明白了，谢谢！", next: -1}
                                ]}
                            ];
                            break;
                        case 'miner':
                            npc.dialog = [
                                {text: "这山上的石头可不简单，要知道如何正确开采。", responses: [
                                    {text: "能教我如何采矿吗？", next: 1},
                                    {text: "我对采矿不感兴趣。", next: -1}
                                ]},
                                {text: "首先需要一把结实的镐，然后找到正确的矿脉。不同颜色的岩石代表不同的矿物。", responses: [
                                    {text: "我该如何识别有价值的矿石？", next: 2},
                                    {text: "谢谢指导，我会尝试的。", next: -1}
                                ]},
                                {text: "有光泽的通常是金属矿，透明的可能是水晶，带有色彩的往往有特殊用途。", responses: [
                                    {text: "了解了，多谢！", next: -1}
                                ]}
                            ];
                            break;
                    }
                } else {
                    // 敌对NPC设置
                    this.ecs.addComponent(npcEntity, new HealthComponent(50));
                    this.ecs.addComponent(npcEntity, new CombatComponent(15, 5));
                    
                    if (id === 'wolf') {
                        this.ecs.getComponent(npcEntity, 'HealthComponent').max = 40;
                        this.ecs.getComponent(npcEntity, 'HealthComponent').current = 40;
                        this.ecs.getComponent(npcEntity, 'CombatComponent').attack = 12;
                        this.ecs.getComponent(npcEntity, 'CombatComponent').defense = 3;
                    }
                }
                
                this.ecs.addComponent(npcEntity, npc);
                return npcEntity;
            }

            createTask(id, title, description, reward, requirements) {
                const taskEntity = this.ecs.createEntity();
                this.ecs.addComponent(taskEntity, new NameComponent(title));
                const task = new TaskComponent(title, description, reward);
                task.id = id;
                task.requirements = requirements;
                this.ecs.addComponent(taskEntity, task);
                return taskEntity;
            }

            createRecipe(id, name, ingredients, category) {
                const recipeEntity = this.ecs.createEntity();
                this.ecs.addComponent(recipeEntity, new NameComponent(name));
                this.ecs.addComponent(recipeEntity, {
                    constructor: {name: 'RecipeComponent'},
                    id: id,
                    ingredients: ingredients,
                    category: category
                });
                return recipeEntity;
            }

            createBuilding(id, name, resources) {
                const buildingEntity = this.ecs.createEntity();
                this.ecs.addComponent(buildingEntity, new NameComponent(name));
                this.ecs.addComponent(buildingEntity, new BuildingComponent(id, resources));
                return buildingEntity;
            }

            createPlayer(name, gender, characterClass) {
                const playerEntity = this.ecs.createEntity();
                this.ecs.addComponent(playerEntity, new NameComponent(name));
                this.ecs.addComponent(playerEntity, new PositionComponent(0, 0, 'camp'));
                this.ecs.addComponent(playerEntity, new HealthComponent(100));
                this.ecs.addComponent(playerEntity, new HungerComponent(100));
                this.ecs.addComponent(playerEntity, new EnergyComponent(100));
                this.ecs.addComponent(playerEntity, new InventoryComponent(20));
                
                let strength = 10, agility = 10, intelligence = 10, endurance = 10;
                
                switch(characterClass) {
                    case 'hunter':
                        strength = 12;
                        agility = 14;
                        endurance = 12;
                        intelligence = 8;
                        break;
                    case 'gatherer':
                        strength = 8;
                        agility = 12;
                        endurance = 10;
                        intelligence = 14;
                        break;
                    case 'builder':
                        strength = 14;
                        agility = 8;
                        endurance = 14;
                        intelligence = 10;
                        break;
                }
                
                this.ecs.addComponent(playerEntity, new AttributesComponent(strength, agility, intelligence, endurance));
                this.ecs.addComponent(playerEntity, new SkillsComponent());
                this.ecs.addComponent(playerEntity, new LevelComponent());
                this.ecs.addComponent(playerEntity, new PlayerComponent(gender, characterClass));
                this.ecs.addComponent(playerEntity, new CombatComponent(strength / 2, endurance / 2));
                
                // 根据职业给予初始物品
                const inventory = this.ecs.getComponent(playerEntity, 'InventoryComponent');
                inventory.addItem('water', 5);
                inventory.addItem('food_ration', 3);
                
                switch(characterClass) {
                    case 'hunter':
                        inventory.addItem('knife', 1);
                        break;
                    case 'gatherer':
                        inventory.addItem('bag', 1);
                        inventory.capacity += 5;
                        break;
                    case 'builder':
                        inventory.addItem('hammer', 1);
                        break;
                }
                
                this.player = playerEntity;
                return playerEntity;
            }

            startGameLoop() {
                this.gameRunning = true;
                this.lastUpdate = Date.now();
                
                const gameLoop = () => {
                    if (!this.gameRunning) return;
                    
                    const now = Date.now();
                    const deltaTime = (now - this.lastUpdate) / 1000 * this.gameSpeed;
                    this.lastUpdate = now;
                    
                    this.time += deltaTime;
                    this.ecs.update(deltaTime);
                    
                    requestAnimationFrame(gameLoop);
                };
                
                gameLoop();
            }

            pauseGame() {
                this.gameRunning = false;
            }

            resumeGame() {
                if (!this.gameRunning) {
                    this.gameRunning = true;
                    this.lastUpdate = Date.now();
                    this.startGameLoop();
                }
            }

            saveGame() {
                const saveData = {
                    player: this.player,
                    currentLocation: this.currentLocation,
                    time: this.time,
                    entities: Array.from(this.ecs.entities.entries()),
                    components: this.ecs.components,
                    nextEntityId: this.ecs.nextEntityId
                };
                
                localStorage.setItem('mudSurvivalSave', JSON.stringify(saveData));
                return true;
            }

            loadGame() {
                const saveData = localStorage.getItem('mudSurvivalSave');
                if (!saveData) return false;
                
                try {
                    const data = JSON.parse(saveData);
                    this.player = data.player;
                    this.currentLocation = data.currentLocation;
                    this.time = data.time;
                    
                    // 重建ECS系统
                    this.ecs = new ECS();
                    this.ecs.entities = new Map(data.entities);
                    this.ecs.components = data.components;
                    this.ecs.nextEntityId = data.nextEntityId;
                    
                    // 重新初始化系统
                    this.ecs.addSystem(new ResourceSystem());
                    this.ecs.addSystem(new HealthSystem());
                    this.ecs.addSystem(new HungerSystem());
                    this.ecs.addSystem(new EnergySystem());
                    
                    return true;
                } catch (e) {
                    console.error("加载存档失败:", e);
                    return false;
                }
            }

            collectResource(resourceEntity, amount) {
                if (!this.player) return false;
                
                const resource = this.ecs.getComponent(resourceEntity, 'ResourceComponent');
                if (!resource || resource.amount < amount) return false;
                
                const playerPosition = this.ecs.getComponent(this.player, 'PositionComponent');
                const resourcePosition = this.ecs.getComponent(resourceEntity, 'PositionComponent');
                
                if (playerPosition.location !== resourcePosition.location) return false;
                
                const playerInventory = this.ecs.getComponent(this.player, 'InventoryComponent');
                const playerEnergy = this.ecs.getComponent(this.player, 'EnergyComponent');
                
                // 检查精力是否足够
                if (playerEnergy.current < 5) {
                    gameLog("你没有足够的精力来收集资源。");
                    return false;
                }
                
                // 消耗精力
                playerEnergy.current -= 5;
                
                // 根据技能计算收集效率
                const playerSkills = this.ecs.getComponent(this.player, 'SkillsComponent');
                const efficiency = 1 + playerSkills.gathering * 0.1;
                const actualAmount = Math.min(resource.amount, Math.ceil(amount * efficiency));
                
                // 根据资源类型添加到物品栏
                let resourceItemId = '';
                switch(resource.type) {
                    case 'wood': resourceItemId = 'wood'; break;
                    case 'stone': resourceItemId = 'stone'; break;
                    case 'herb': resourceItemId = 'herb'; break;
                    case 'ore': resourceItemId = 'ore'; break;
                    case 'crystal': resourceItemId = 'crystal'; break;
                    case 'fish': resourceItemId = 'fish'; break;
                    case 'reed': resourceItemId = 'reed'; break;
                    case 'grass': resourceItemId = 'grass'; break;
                    case 'fruit': resourceItemId = 'fruit'; break;
                }
                
                if (resourceItemId) {
                    playerInventory.addItem(resourceItemId, actualAmount);
                    resource.amount -= actualAmount;
                    
                    // 增加经验
                    const playerLevel = this.ecs.getComponent(this.player, 'LevelComponent');
                    const expGained = actualAmount * 2;
                    playerLevel.addExperience(expGained);
                    
                    // 提高技能
                    playerSkills.gathering += 0.01 * actualAmount;
                    
                    gameLog(`你收集了 ${actualAmount} 个 ${resourceItemId}，获得了 ${expGained} 经验。`);
                    
                    // 检查资源是否耗尽，设置重生时间
                    if (resource.amount <= 0) {
                        const respawnMinutes = Math.floor(Math.random() * 20) + 10;
                        resource.respawnTime = respawnMinutes * 60;
                        gameLog(`这个资源已经被采集完了，大约需要 ${respawnMinutes} 分钟恢复。`);
                    }
                    
                    updateInventory();
                    updateStatusBars();
                    updateCharacterInfo();
                    
                    return true;
                }
                
                return false;
            }

            craft(recipeId) {
                if (!this.player) return false;
                
                // 查找配方
                let recipe = null;
                let recipeEntity = null;
                
                for (const [entityId, nameComponent] of Object.entries(this.ecs.components['NameComponent'])) {
                    const recipeComponent = this.ecs.getComponent(entityId, 'RecipeComponent');
                    if (recipeComponent && recipeComponent.id === recipeId) {
                        recipe = recipeComponent;
                        recipeEntity = entityId;
                        break;
                    }
                }
                
                if (!recipe) return false;
                
                const playerInventory = this.ecs.getComponent(this.player, 'InventoryComponent');
                const playerEnergy = this.ecs.getComponent(this.player, 'EnergyComponent');
                
                // 检查精力是否足够
                if (playerEnergy.current < 10) {
                    gameLog("你没有足够的精力来合成物品。");
                    return false;
                }
                
                // 检查材料是否足够
                for (const [itemId, amount] of Object.entries(recipe.ingredients)) {
                    if (!playerInventory.hasItem(itemId, amount)) {
                        gameLog(`你没有足够的材料来合成 ${this.ecs.getComponent(recipeEntity, 'NameComponent').name}。`);
                        return false;
                    }
                }
                
                // 消耗材料
                for (const [itemId, amount] of Object.entries(recipe.ingredients)) {
                    playerInventory.removeItem(itemId, amount);
                }
                
                // 消耗精力
                playerEnergy.current -= 10;
                
                // 添加产品到物品栏
                playerInventory.addItem(recipe.id, 1);
                
                // 增加经验和技能
                const playerLevel = this.ecs.getComponent(this.player, 'LevelComponent');
                const playerSkills = this.ecs.getComponent(this.player, 'SkillsComponent');
                
                const expGained = Object.values(recipe.ingredients).reduce((a, b) => a + b, 0) * 5;
                playerLevel.addExperience(expGained);
                playerSkills.crafting += 0.05;
                
                gameLog(`你成功合成了 ${this.ecs.getComponent(recipeEntity, 'NameComponent').name}，获得了 ${expGained} 经验。`);
                
                updateInventory();
                updateStatusBars();
                updateCharacterInfo();
                
                return true;
            }

            build(buildingId) {
                if (!this.player) return false;
                
                // 查找建筑
                let building = null;
                let buildingEntity = null;
                
                for (const [entityId, nameComponent] of Object.entries(this.ecs.components['NameComponent'])) {
                    const buildingComponent = this.ecs.getComponent(entityId, 'BuildingComponent');
                    if (buildingComponent && buildingComponent.type === buildingId) {
                        building = buildingComponent;
                        buildingEntity = entityId;
                        break;
                    }
                }
                
                if (!building) return false;
                
                const playerInventory = this.ecs.getComponent(this.player, 'InventoryComponent');
                const playerEnergy = this.ecs.getComponent(this.player, 'EnergyComponent');
                const playerPosition = this.ecs.getComponent(this.player, 'PositionComponent');
                
                // 检查精力是否足够
                if (playerEnergy.current < 20) {
                    gameLog("你没有足够的精力来建造。");
                    return false;
                }
                
                // 检查材料是否足够
                for (const [itemId, amount] of Object.entries(building.resources)) {
                    if (!playerInventory.hasItem(itemId, amount)) {
                        gameLog(`你没有足够的材料来建造 ${this.ecs.getComponent(buildingEntity, 'NameComponent').name}。`);
                        return false;
                    }
                }
                
                // 消耗材料
                for (const [itemId, amount] of Object.entries(building.resources)) {
                    playerInventory.removeItem(itemId, amount);
                }
                
                // 消耗精力
                playerEnergy.current -= 20;
                
                // 创建建筑实例
                const newBuildingEntity = this.ecs.createEntity();
                this.ecs.addComponent(newBuildingEntity, new NameComponent(this.ecs.getComponent(buildingEntity, 'NameComponent').name));
                this.ecs.addComponent(newBuildingEntity, new PositionComponent(0, 0, playerPosition.location));
                const newBuilding = new BuildingComponent(building.type, {});
                newBuilding.completed = true;
                this.ecs.addComponent(newBuildingEntity, newBuilding);
                
                // 增加经验和技能
                const playerLevel = this.ecs.getComponent(this.player, 'LevelComponent');
                const playerSkills = this.ecs.getComponent(this.player, 'SkillsComponent');
                
                const expGained = Object.values(building.resources).reduce((a, b) => a + b, 0) * 10;
                playerLevel.addExperience(expGained);
                playerSkills.building += 0.1;
                
                gameLog(`你成功建造了 ${this.ecs.getComponent(buildingEntity, 'NameComponent').name}，获得了 ${expGained} 经验。`);
                
                updateInventory();
                updateStatusBars();
                updateCharacterInfo();
                
                return true;
            }

            fight(targetEntity) {
                if (!this.player) return false;
                
                const playerPosition = this.ecs.getComponent(this.player, 'PositionComponent');
                const targetPosition = this.ecs.getComponent(targetEntity, 'PositionComponent');
                
                if (playerPosition.location !== targetPosition.location) return false;
                
                const playerHealth = this.ecs.getComponent(this.player, 'HealthComponent');
                const targetHealth = this.ecs.getComponent(targetEntity, 'HealthComponent');
                
                const playerCombat = this.ecs.getComponent(this.player, 'CombatComponent');
                const targetCombat = this.ecs.getComponent(targetEntity, 'CombatComponent');
                
                const playerEnergy = this.ecs.getComponent(this.player, 'EnergyComponent');
                
                // 检查精力是否足够
                if (playerEnergy.current < 15) {
                    gameLog("你没有足够的精力来战斗。");
                    return false;
                }
                
                // 消耗精力
                playerEnergy.current -= 15;
                
                // 战斗计算
                const targetName = this.ecs.getComponent(targetEntity, 'NameComponent').name;
                
                // 玩家攻击
                const playerDamage = Math.max(1, playerCombat.attack - targetCombat.defense / 2);
                targetHealth.current -= playerDamage;
                gameLog(`你对 ${targetName} 造成了 ${playerDamage} 点伤害。`);
                
                // 目标反击
                if (targetHealth.current > 0) {
                    const targetDamage = Math.max(1, targetCombat.attack - playerCombat.defense / 2);
                    playerHealth.current -= targetDamage;
                    gameLog(`${targetName} 对你造成了 ${targetDamage} 点伤害。`);
                } else {
                    gameLog(`你击败了 ${targetName}！`);
                    
                    // 增加经验和技能
                    const playerLevel = this.ecs.getComponent(this.player, 'LevelComponent');
                    const playerSkills = this.ecs.getComponent(this.player, 'SkillsComponent');
                    
                    const expGained = targetHealth.max * 2;
                    playerLevel.addExperience(expGained);
                    playerSkills.combat += 0.05;
                    
                    gameLog(`你获得了 ${expGained} 经验。`);
                }
                
                updateStatusBars();
                updateCharacterInfo();
                
                return true;
            }

            moveToLocation(locationId) {
                if (!this.player) return false;
                
                const playerPosition = this.ecs.getComponent(this.player, 'PositionComponent');
                const currentLocation = playerPosition.location;
                
                // 检查位置是否相连
                let canMove = false;
                for (const [entityId, locationComponent] of Object.entries(this.ecs.components['LocationComponent'])) {
                    if (locationComponent.id === currentLocation) {
                        if (locationComponent.connected.includes(locationId)) {
                            canMove = true;
                        }
                        break;
                    }
                }
                
                if (!canMove) {
                    gameLog(`你无法从 ${getLocationName(currentLocation)} 直接前往 ${getLocationName(locationId)}。`);
                    return false;
                }
                
                const playerEnergy = this.ecs.getComponent(this.player, 'EnergyComponent');
                
                // 检查精力是否足够
                if (playerEnergy.current < 10) {
                    gameLog("你没有足够的精力来移动。");
                    return false;
                }
                
                // 消耗精力
                playerEnergy.current -= 10;
                
                // 更新位置
                playerPosition.location = locationId;
                this.currentLocation = locationId;
                
                gameLog(`你来到了 ${getLocationName(locationId)}。`);
                describeLocation(locationId);
                
                updateStatusBars();
                updateMap();
                
                return true;
            }

            useItem(itemId) {
                if (!this.player) return false;
                
                const playerInventory = this.ecs.getComponent(this.player, 'InventoryComponent');
                
                if (!playerInventory.hasItem(itemId, 1)) {
                    gameLog(`你没有 ${getItemName(itemId)}。`);
                    return false;
                }
                
                let used = false;
                
                switch(itemId) {
                    case 'food_ration':
                        const hunger = this.ecs.getComponent(this.player, 'HungerComponent');
                        hunger.current = Math.min(hunger.max, hunger.current + 30);
                        used = true;
                        gameLog("你吃了一份食物，饥饿度恢复了。");
                        break;
                    case 'water':
                        const energy = this.ecs.getComponent(this.player, 'EnergyComponent');
                        energy.current = Math.min(energy.max, energy.current + 20);
                        used = true;
                        gameLog("你喝了一些水，精力恢复了。");
                        break;
                    case 'cooked_meat':
                        const health = this.ecs.getComponent(this.player, 'HealthComponent');
                        const hungerForMeat = this.ecs.getComponent(this.player, 'HungerComponent');
                        health.current = Math.min(health.max, health.current + 10);
                        hungerForMeat.current = Math.min(hungerForMeat.max, hungerForMeat.current + 40);
                        used = true;
                        gameLog("你吃了烤肉，恢复了一些生命值和饥饿度。");
                        break;
                    case 'medicine_basic':
                        const healthForMed = this.ecs.getComponent(this.player, 'HealthComponent');
                        healthForMed.current = Math.min(healthForMed.max, healthForMed.current + 30);
                        used = true;
                        gameLog("你使用了药物，恢复了一些生命值。");
                        break;
                    case 'fruit':
                        const hungerForFruit = this.ecs.getComponent(this.player, 'HungerComponent');
                        hungerForFruit.current = Math.min(hungerForFruit.max, hungerForFruit.current + 15);
                        const energyForFruit = this.ecs.getComponent(this.player, 'EnergyComponent');
                        energyForFruit.current = Math.min(energyForFruit.max, energyForFruit.current + 10);
                        used = true;
                        gameLog("你吃了水果，恢复了一些饥饿度和精力。");
                        break;
                    default:
                        gameLog(`${getItemName(itemId)}不能直接使用。`);
                        return false;
                }
                
                if (used) {
                    playerInventory.removeItem(itemId, 1);
                    updateInventory();
                    updateStatusBars();
                    return true;
                }
                
                return false;
            }

            completeTask(taskId) {
                if (!this.player) return false;
                
                // 查找任务
                let task = null;
                let taskEntity = null;
                
                for (const [entityId, component] of Object.entries(this.ecs.components['TaskComponent'])) {
                    if (component.id === taskId) {
                        task = component;
                        taskEntity = entityId;
                        break;
                    }
                }
                
                if (!task || task.completed) return false;
                
                const playerInventory = this.ecs.getComponent(this.player, 'InventoryComponent');
                
                // 检查需求是否满足
                for (const [itemId, amount] of Object.entries(task.requirements)) {
                    if (!playerInventory.hasItem(itemId, amount)) {
                        gameLog(`你尚未完成任务"${task.title}"的要求。`);
                        return false;
                    }
                }
                
                // 消耗需求物品
                for (const [itemId, amount] of Object.entries(task.requirements)) {
                    playerInventory.removeItem(itemId, amount);
                }
                
                // 奖励
                if (task.reward.exp) {
                    const playerLevel = this.ecs.getComponent(this.player, 'LevelComponent');
                    playerLevel.addExperience(task.reward.exp);
                    gameLog(`你获得了 ${task.reward.exp} 经验。`);
                }
                
                if (task.reward.items) {
                    for (const [itemId, amount] of Object.entries(task.reward.items)) {
                        playerInventory.addItem(itemId, amount);
                        gameLog(`你获得了 ${amount} 个 ${getItemName(itemId)}。`);
                    }
                }
                
                if (task.reward.skill) {
                    const playerSkills = this.ecs.getComponent(this.player, 'SkillsComponent');
                    for (const [skillName, amount] of Object.entries(task.reward.skill)) {
                        playerSkills[skillName] += amount;
                        gameLog(`你的${getSkillName(skillName)}技能提高了 ${amount} 级。`);
                    }
                }
                
                task.completed = true;
                gameLog(`任务"${task.title}"完成！`);
                
                updateInventory();
                updateTasks();
                updateCharacterInfo();
                
                return true;
            }

            talkToNPC(npcEntity) {
                if (!this.player) return false;
                
                const playerPosition = this.ecs.getComponent(this.player, 'PositionComponent');
                const npcPosition = this.ecs.getComponent(npcEntity, 'PositionComponent');
                
                if (playerPosition.location !== npcPosition.location) return false;
                
                const npc = this.ecs.getComponent(npcEntity, 'NPCComponent');
                const npcName = this.ecs.getComponent(npcEntity, 'NameComponent').name;
                
                if (!npc.friendly) {
                    gameLog(`${npcName}对你表现出敌意！`);
                    return false;
                }
                
                if (npc.dialog && npc.dialog.length > 0) {
                    showDialog(npcEntity, 0);
                    return true;
                } else {
                    gameLog(`${npcName}现在没什么可说的。`);
                    return false;
                }
            }
        }

        const gameState = new GameState();

        // 辅助函数
        function getPlayerEntity() {
            return gameState.player;
        }

        function getLocationName(locationId) {
            for (const [entityId, locationComponent] of Object.entries(gameState.ecs.components['LocationComponent'])) {
                if (locationComponent.id === locationId) {
                    return gameState.ecs.getComponent(entityId, 'NameComponent').name;
                }
            }
            return locationId;
        }

        function getLocationDescription(locationId) {
            for (const [entityId, locationComponent] of Object.entries(gameState.ecs.components['LocationComponent'])) {
                if (locationComponent.id === locationId) {
                    return locationComponent.description;
                }
            }
            return "";
        }

        function getEntitiesAtLocation(locationId) {
            const entities = [];
            
            if (!gameState.ecs.components['PositionComponent']) return entities;
            
            for (const [entityId, position] of Object.entries(gameState.ecs.components['PositionComponent'])) {
                if (position.location === locationId) {
                    entities.push(entityId);
                }
            }
            
            return entities;
        }

        function getItemName(itemId) {
            const itemNames = {
                'wood': '木材',
                'stone': '石头',
                'herb': '草药',
                'ore': '矿石',
                'crystal': '水晶',
                'fish': '鱼',
                'reed': '芦苇',
                'grass': '草',
                'fruit': '水果',
                'meat': '肉',
                'hide': '皮革',
                'tool_basic': '基础工具',
                'weapon_spear': '长矛',
                'cooked_meat': '烤肉',
                'medicine_basic': '基础药物',
                'food_ration': '食物口粮',
                'water': '水',
                'knife': '小刀',
                'bag': '背包',
                'hammer': '锤子'
            };
            
            return itemNames[itemId] || itemId;
        }

        function getSkillName(skillId) {
            const skillNames = {
                'gathering': '采集',
                'building': '建造',
                'combat': '战斗',
                'crafting': '合成'
            };
            
            return skillNames[skillId] || skillId;
        }

        // UI 函数
        function gameLog(message) {
            const gameLogElement = document.getElementById('game-log');
            const messageElement = document.createElement('div');
            messageElement.textContent = message;
            gameLogElement.appendChild(messageElement);
            gameLogElement.scrollTop = gameLogElement.scrollHeight;
        }

        function updateStatusBars() {
            if (!gameState.player) return;
            
            const health = gameState.ecs.getComponent(gameState.player, 'HealthComponent');
            const hunger = gameState.ecs.getComponent(gameState.player, 'HungerComponent');
            const energy = gameState.ecs.getComponent(gameState.player, 'EnergyComponent');
            
            document.getElementById('health-value').textContent = Math.floor(health.current);
            document.getElementById('health-max').textContent = health.max;
            document.getElementById('health-bar').style.width = `${(health.current / health.max) * 100}%`;
            
            document.getElementById('hunger-value').textContent = Math.floor(hunger.current);
            document.getElementById('hunger-max').textContent = hunger.max;
            document.getElementById('hunger-bar').style.width = `${(hunger.current / hunger.max) * 100}%`;
            
            document.getElementById('energy-value').textContent = Math.floor(energy.current);
            document.getElementById('energy-max').textContent = energy.max;
            document.getElementById('energy-bar').style.width = `${(energy.current / energy.max) * 100}%`;
        }

        function updateCharacterInfo() {
            if (!gameState.player) return;
            
            const name = gameState.ecs.getComponent(gameState.player, 'NameComponent').name;
            const player = gameState.ecs.getComponent(gameState.player, 'PlayerComponent');
            const level = gameState.ecs.getComponent(gameState.player, 'LevelComponent');
            const attributes = gameState.ecs.getComponent(gameState.player, 'AttributesComponent');
            const skills = gameState.ecs.getComponent(gameState.player, 'SkillsComponent');
            
            document.getElementById('char-name').textContent = name;
            document.getElementById('char-gender').textContent = player.gender === 'male' ? '男' : '女';
            document.getElementById('char-class').textContent = {
                'hunter': '猎人',
                'gatherer': '采集者',
                'builder': '建造者'
            }[player.characterClass] || player.characterClass;
            
            document.getElementById('char-level').textContent = level.level;
            document.getElementById('char-exp').textContent = level.experience;
            document.getElementById('char-next-exp').textContent = level.nextLevelExp;
            
            document.getElementById('attr-strength').textContent = Math.floor(attributes.strength);
            document.getElementById('attr-agility').textContent = Math.floor(attributes.agility);
            document.getElementById('attr-intelligence').textContent = Math.floor(attributes.intelligence);
            document.getElementById('attr-endurance').textContent = Math.floor(attributes.endurance);
            
            document.getElementById('skill-gathering').textContent = Math.floor(skills.gathering);
            document.getElementById('skill-building').textContent = Math.floor(skills.building);
            document.getElementById('skill-combat').textContent = Math.floor(skills.combat);
            document.getElementById('skill-crafting').textContent = Math.floor(skills.crafting);
        }

        function updateInventory() {
            if (!gameState.player) return;
            
            const inventory = gameState.ecs.getComponent(gameState.player, 'InventoryComponent');
            const inventoryList = document.getElementById('inventory-list');
            
            inventoryList.innerHTML = '';
            
            for (const [itemId, amount] of Object.entries(inventory.items)) {
                const itemElement = document.createElement('div');
                itemElement.className = 'inventory-item';
                
                const iconElement = document.createElement('div');
                iconElement.className = 'item-icon';
                iconElement.textContent = itemId.charAt(0).toUpperCase();
                
                const nameElement = document.createElement('div');
                nameElement.className = 'item-name';
                nameElement.textContent = `${getItemName(itemId)} x${amount}`;
                
                const actionsElement = document.createElement('div');
                actionsElement.className = 'item-actions';
                
                const useButton = document.createElement('button');
                useButton.className = 'game-button';
                useButton.textContent = '使用';
                useButton.onclick = () => gameState.useItem(itemId);
                
                itemElement.appendChild(iconElement);
                itemElement.appendChild(nameElement);
                itemElement.appendChild(actionsElement);
                actionsElement.appendChild(useButton);
                
                inventoryList.appendChild(itemElement);
            }
            
            if (Object.keys(inventory.items).length === 0) {
                inventoryList.innerHTML = '<p>你的物品栏是空的。</p>';
            }
        }

        function updateRecipes() {
            if (!gameState.player) return;
            
            const recipeList = document.getElementById('recipe-list');
            recipeList.innerHTML = '';
            
            if (!gameState.ecs.components['RecipeComponent']) return;
            
            for (const [entityId, recipe] of Object.entries(gameState.ecs.components['RecipeComponent'])) {
                const nameComponent = gameState.ecs.getComponent(entityId, 'NameComponent');
                
                const recipeElement = document.createElement('div');
                recipeElement.className = 'recipe-item';
                
                const nameElement = document.createElement('h4');
                nameElement.textContent = nameComponent.name;
                
                const ingredientsElement = document.createElement('p');
                let ingredientsText = '需要: ';
                for (const [itemId, amount] of Object.entries(recipe.ingredients)) {
                    ingredientsText += `${getItemName(itemId)} x${amount}, `;
                }
                ingredientsElement.textContent = ingredientsText.slice(0, -2);
                
                const craftButton = document.createElement('button');
                craftButton.className = 'game-button';
                craftButton.textContent = '合成';
                craftButton.onclick = () => gameState.craft(recipe.id);
                
                recipeElement.appendChild(nameElement);
                recipeElement.appendChild(ingredientsElement);
                recipeElement.appendChild(craftButton);
                
                recipeList.appendChild(recipeElement);
            }
            
            if (recipeList.children.length === 0) {
                recipeList.innerHTML = '<p>没有可用的合成配方。</p>';
            }
        }

        function updateBuildings() {
            if (!gameState.player) return;
            
            const buildingList = document.getElementById('building-list');
            buildingList.innerHTML = '';
            
            if (!gameState.ecs.components['BuildingComponent']) return;
            
            for (const [entityId, building] of Object.entries(gameState.ecs.components['BuildingComponent'])) {
                if (!building.completed) { // 只显示可建造的建筑
                    const nameComponent = gameState.ecs.getComponent(entityId, 'NameComponent');
                    
                    const buildingElement = document.createElement('div');
                    buildingElement.className = 'building-item';
                    
                    const nameElement = document.createElement('h4');
                    nameElement.textContent = nameComponent.name;
                    
                    const resourcesElement = document.createElement('p');
                    let resourcesText = '需要: ';
                    for (const [itemId, amount] of Object.entries(building.resources)) {
                        resourcesText += `${getItemName(itemId)} x${amount}, `;
                    }
                    resourcesElement.textContent = resourcesText.slice(0, -2);
                    
                    const buildButton = document.createElement('button');
                    buildButton.className = 'game-button';
                    buildButton.textContent = '建造';
                    buildButton.onclick = () => gameState.build(building.type);
                    
                    buildingElement.appendChild(nameElement);
                    buildingElement.appendChild(resourcesElement);
                    buildingElement.appendChild(buildButton);
                    
                    buildingList.appendChild(buildingElement);
                }
            }
            
            if (buildingList.children.length === 0) {
                buildingList.innerHTML = '<p>没有可用的建筑。</p>';
            }
        }

        function updateTasks() {
            if (!gameState.player) return;
            
            const taskList = document.getElementById('task-list');
            taskList.innerHTML = '';
            
            if (!gameState.ecs.components['TaskComponent']) return;
            
            for (const [entityId, task] of Object.entries(gameState.ecs.components['TaskComponent'])) {
                const taskElement = document.createElement('div');
                taskElement.className = 'task-item';
                
                const titleElement = document.createElement('h4');
                titleElement.textContent = task.title + (task.completed ? ' (已完成)' : '');
                
                const descriptionElement = document.createElement('p');
                descriptionElement.textContent = task.description;
                
                const requirementsElement = document.createElement('p');
                let requirementsText = '需要: ';
                for (const [itemId, amount] of Object.entries(task.requirements)) {
                    requirementsText += `${getItemName(itemId)} x${amount}, `;
                }
                requirementsElement.textContent = requirementsText.slice(0, -2);
                
                const rewardElement = document.createElement('p');
                let rewardText = '奖励: ';
                if (task.reward.exp) {
                    rewardText += `经验 ${task.reward.exp}, `;
                }
                if (task.reward.items) {
                    for (const [itemId, amount] of Object.entries(task.reward.items)) {
                        rewardText += `${getItemName(itemId)} x${amount}, `;
                    }
                }
                if (task.reward.skill) {
                    for (const [skillName, amount] of Object.entries(task.reward.skill)) {
                        rewardText += `${getSkillName(skillName)} +${amount}, `;
                    }
                }
                rewardElement.textContent = rewardText.slice(0, -2);
                
                taskElement.appendChild(titleElement);
                taskElement.appendChild(descriptionElement);
                taskElement.appendChild(requirementsElement);
                taskElement.appendChild(rewardElement);
                
                if (!task.completed) {
                    const completeButton = document.createElement('button');
                    completeButton.className = 'game-button';
                    completeButton.textContent = '完成任务';
                    completeButton.onclick = () => gameState.completeTask(task.id);
                    
                    taskElement.appendChild(completeButton);
                }
                
                taskList.appendChild(taskElement);
            }
            
            if (taskList.children.length === 0) {
                taskList.innerHTML = '<p>没有可用的任务。</p>';
            }
        }

        function updateMap() {
            if (!gameState.player) return;
            
            const currentLocation = document.getElementById('current-location');
            const availableLocations = document.getElementById('available-locations');
            
            const playerPosition = gameState.ecs.getComponent(gameState.player, 'PositionComponent');
            
            currentLocation.innerHTML = '';
            availableLocations.innerHTML = '';
            
            // 当前位置
            const currentHeader = document.createElement('h4');
            currentHeader.textContent = '当前位置';
            
            const locationName = document.createElement('p');
            locationName.textContent = getLocationName(playerPosition.location);
            
            const locationDesc = document.createElement('p');
            locationDesc.textContent = getLocationDescription(playerPosition.location);
            
            currentLocation.appendChild(currentHeader);
            currentLocation.appendChild(locationName);
            currentLocation.appendChild(locationDesc);
            
            // 可前往的位置
            const availableHeader = document.createElement('h4');
            availableHeader.textContent = '可前往的位置';
            availableLocations.appendChild(availableHeader);
            
            for (const [entityId, locationComponent] of Object.entries(gameState.ecs.components['LocationComponent'])) {
                if (locationComponent.id === playerPosition.location) {
                    for (const connectedId of locationComponent.connected) {
                        const locationButton = document.createElement('button');
                        locationButton.className = 'game-button';
                        locationButton.textContent = getLocationName(connectedId);
                        locationButton.onclick = () => gameState.moveToLocation(connectedId);
                        
                        availableLocations.appendChild(locationButton);
                    }
                    break;
                }
            }
        }

        function describeLocation(locationId) {
            const entities = getEntitiesAtLocation(locationId);
            
            gameLog(`这里是${getLocationName(locationId)}。${getLocationDescription(locationId)}`);
            
            // 列出资源
            const resources = [];
            
            for (const entityId of entities) {
                const resource = gameState.ecs.getComponent(entityId, 'ResourceComponent');
                if (resource && resource.amount > 0) {
                    const name = gameState.ecs.getComponent(entityId, 'NameComponent').name;
                    resources.push(name);
                }
            }
            
            if (resources.length > 0) {
                gameLog(`这里有: ${resources.join(', ')}`);
            }
            
            // 列出NPC
            const npcs = [];
            
            for (const entityId of entities) {
                const npc = gameState.ecs.getComponent(entityId, 'NPCComponent');
                if (npc) {
                    const name = gameState.ecs.getComponent(entityId, 'NameComponent').name;
                    npcs.push(name);
                }
            }
            
            if (npcs.length > 0) {
                gameLog(`这里有: ${npcs.join(', ')}`);
            }
            
            // 列出建筑
            const buildings = [];
            
            for (const entityId of entities) {
                const building = gameState.ecs.getComponent(entityId, 'BuildingComponent');
                if (building && building.completed) {
                    const name = gameState.ecs.getComponent(entityId, 'NameComponent').name;
                    buildings.push(name);
                }
            }
            
            if (buildings.length > 0) {
                gameLog(`这里有: ${buildings.join(', ')}`);
            }
        }

        function showDialog(npcEntity, dialogIndex) {
            const npc = gameState.ecs.getComponent(npcEntity, 'NPCComponent');
            const npcName = gameState.ecs.getComponent(npcEntity, 'NameComponent').name;
            
            if (dialogIndex < 0 || dialogIndex >= npc.dialog.length) return;
            
            const dialogElement = document.createElement('div');
            dialogElement.className = 'dialog';
            
            const dialog = npc.dialog[dialogIndex];
            
            const speakerElement = document.createElement('div');
            speakerElement.className = 'dialog-speaker';
            speakerElement.textContent = npcName;
            
            const textElement = document.createElement('div');
            textElement.className = 'dialog-text';
            textElement.textContent = dialog.text;
            
            dialogElement.appendChild(speakerElement);
            dialogElement.appendChild(textElement);
            
            if (dialog.responses && dialog.responses.length > 0) {
                const responsesElement = document.createElement('div');
                responsesElement.className = 'dialog-responses';
                
                for (const response of dialog.responses) {
                    const responseButton = document.createElement('button');
                    responseButton.className = 'game-button';
                    responseButton.textContent = response.text;
                    
                    if (response.next >= 0) {
                        responseButton.onclick = () => {
                            gameLog(`你: ${response.text}`);
                            dialogElement.remove();
                            showDialog(npcEntity, response.next);
                        };
                    } else {
                        responseButton.onclick = () => {
                            gameLog(`你: ${response.text}`);
                            dialogElement.remove();
                        };
                    }
                    
                    responsesElement.appendChild(responseButton);
                }
                
                dialogElement.appendChild(responsesElement);
            }
            
            gameLog(`${npcName}: ${dialog.text}`);
            document.getElementById('game-log').appendChild(dialogElement);
            document.getElementById('game-log').scrollTop = document.getElementById('game-log').scrollHeight;
        }

        // 初始化和事件处理
        document.addEventListener('DOMContentLoaded', () => {
            // 初始化游戏
            gameState.init();
            
            // 显示角色创建模态窗
            document.getElementById('character-creation').style.display = 'block';
            
            // 关闭角色创建模态窗事件
            document.getElementById('close-character-creation').addEventListener('click', () => {
                document.getElementById('character-creation').style.display = 'none';
            });
            
            // 创建角色事件
            document.getElementById('create-character').addEventListener('click', () => {
                const name = document.getElementById('character-name').value.trim();
                const gender = document.getElementById('character-gender').value;
                const characterClass = document.getElementById('character-class').value;
                
                if (name === '') {
                    alert('请输入角色名称！');
                    return;
                }
                
                gameState.createPlayer(name, gender, characterClass);
                document.getElementById('character-creation').style.display = 'none';
                
                // 更新UI
                updateCharacterInfo();
                updateStatusBars();
                updateInventory();
                updateRecipes();
                updateBuildings();
                updateTasks();
                updateMap();
                
                // 开始游戏
                gameLog("欢迎来到野外生存创造MUD！");
                gameLog(`你创建了一个${gender === 'male' ? '男' : '女'}性${characterClass === 'hunter' ? '猎人' : (characterClass === 'gatherer' ? '采集者' : '建造者')}：${name}`);
                describeLocation('camp');
            });
            
            // 面板切换事件
            document.querySelectorAll('.menu-item').forEach(menuItem => {
                menuItem.addEventListener('click', () => {
                    document.querySelectorAll('.menu-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    menuItem.classList.add('active');
                    
                    const panelId = menuItem.getAttribute('data-panel');
                    document.querySelectorAll('.panel').forEach(panel => {
                        panel.classList.remove('active');
                    });
                    document.getElementById(`${panelId}-panel`).classList.add('active');
                });
            });
            
            // 命令输入事件
            document.getElementById('submit-command').addEventListener('click', () => {
                processCommand();
            });
            
            document.getElementById('game-input').addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    processCommand();
                }
            });
            
            // 保存游戏事件
            document.getElementById('save-game').addEventListener('click', () => {
                if (gameState.saveGame()) {
                    gameLog("游戏已保存。");
                } else {
                    gameLog("保存游戏失败。");
                }
            });
            
            // 加载游戏事件
            document.getElementById('load-game').addEventListener('click', () => {
                if (gameState.loadGame()) {
                    gameLog("游戏已加载。");
                    
                    // 更新UI
                    updateCharacterInfo();
                    updateStatusBars();
                    updateInventory();
                    updateRecipes();
                    updateBuildings();
                    updateTasks();
                    updateMap();
                    
                    describeLocation(gameState.currentLocation);
                } else {
                    gameLog("没有找到存档或加载失败。");
                }
            });
            
            // 新游戏事件
            document.getElementById('new-game').addEventListener('click', () => {
                if (confirm("确定要开始新游戏吗？当前进度将丢失！")) {
                    location.reload();
                }
            });
            
            // 创造者命令执行事件
            document.getElementById('execute-command').addEventListener('click', () => {
                executeCreatorCommand();
            });
            
            // 初始化合成面板
            updateRecipes();
            
            // 初始化建造面板
            updateBuildings();
            
            // 初始化任务面板
            updateTasks();
        });

        function processCommand() {
            const commandInput = document.getElementById('game-input');
            const command = commandInput.value.trim().toLowerCase();
            
            if (command === '') return;
            
            gameLog(`> ${command}`);
            commandInput.value = '';
            
            if (!gameState.player) {
                gameLog("请先创建角色！");
                return;
            }
            
            const commandParts = command.split(' ');
            const action = commandParts[0];
            
            switch(action) {
                case 'help':
                case '帮助':
                    gameLog("可用命令:");
                    gameLog("查看/look - 查看当前位置");
                    gameLog("采集/collect [资源名] - 采集资源");
                    gameLog("移动/move [位置名] - 移动到指定位置");
                    gameLog("交谈/talk [NPC名] - 与NPC交谈");
                    gameLog("攻击/attack [目标名] - 攻击目标");
                    gameLog("使用/use [物品名] - 使用物品");
                    gameLog("合成/craft [配方名] - 合成物品");
                    gameLog("建造/build [建筑名] - 建造建筑");
                    gameLog("任务/tasks - 查看任务");
                    gameLog("背包/inventory - 查看物品栏");
                    gameLog("状态/status - 查看角色状态");
                    gameLog("保存/save - 保存游戏");
                    gameLog("加载/load - 加载游戏");
                    gameLog("创造/create - 进入创造者模式");
                    gameLog("退出/exit - 退出创造者模式");
                    break;
                
                case 'look':
                case '查看':
                    describeLocation(gameState.ecs.getComponent(gameState.player, 'PositionComponent').location);
                    break;
                
                case 'collect':
                case '采集':
                    if (commandParts.length < 2) {
                        gameLog("请指定要采集的资源名称。");
                        break;
                    }
                    
                    const resourceName = commandParts.slice(1).join(' ');
                    let found = false;
                    
                    const playerPosition = gameState.ecs.getComponent(gameState.player, 'PositionComponent');
                    const entities = getEntitiesAtLocation(playerPosition.location);
                    
                    for (const entityId of entities) {
                        const name = gameState.ecs.getComponent(entityId, 'NameComponent');
                        const resource = gameState.ecs.getComponent(entityId, 'ResourceComponent');
                        
                        if (name && resource && name.name.toLowerCase().includes(resourceName.toLowerCase())) {
                            found = true;
                            if (resource.amount <= 0) {
                                gameLog(`${name.name}已经被采集完了。`);
                            } else {
                                gameState.collectResource(entityId, Math.min(resource.amount, 1));
                            }
                            break;
                        }
                    }
                    
                    if (!found) {
                        gameLog(`这里没有叫"${resourceName}"的资源。`);
                    }
                    break;
                
                case 'move':
                case '移动':
                    if (commandParts.length < 2) {
                        gameLog("请指定要前往的位置名称。");
                        break;
                    }
                    
                    const locationName = commandParts.slice(1).join(' ');
                    let foundLocation = false;
                    
                    for (const [entityId, locationComponent] of Object.entries(gameState.ecs.components['LocationComponent'])) {
                        const name = gameState.ecs.getComponent(entityId, 'NameComponent');
                        
                        if (name && name.name.toLowerCase().includes(locationName.toLowerCase())) {
                            foundLocation = true;
                            gameState.moveToLocation(locationComponent.id);
                            break;
                        }
                    }
                    
                    if (!foundLocation) {
                        gameLog(`没有找到名为"${locationName}"的位置。`);
                    }
                    break;
                
                case 'talk':
                case '交谈':
                    if (commandParts.length < 2) {
                        gameLog("请指定要交谈的NPC名称。");
                        break;
                    }
                    
                    const npcName = commandParts.slice(1).join(' ');
                    let foundNPC = false;
                    
                    const playerPos = gameState.ecs.getComponent(gameState.player, 'PositionComponent');
                    const entitiesHere = getEntitiesAtLocation(playerPos.location);
                    
                    for (const entityId of entitiesHere) {
                        const name = gameState.ecs.getComponent(entityId, 'NameComponent');
                        const npc = gameState.ecs.getComponent(entityId, 'NPCComponent');
                        
                        if (name && npc && name.name.toLowerCase().includes(npcName.toLowerCase())) {
                            foundNPC = true;
                            gameState.talkToNPC(entityId);
                            break;
                        }
                    }
                    
                    if (!foundNPC) {
                        gameLog(`这里没有叫"${npcName}"的NPC。`);
                    }
                    break;
                
                case 'attack':
                case '攻击':
                    if (commandParts.length < 2) {
                        gameLog("请指定要攻击的目标名称。");
                        break;
                    }
                    
                    const targetName = commandParts.slice(1).join(' ');
                    let foundTarget = false;
                    
                    const playerPosition2 = gameState.ecs.getComponent(gameState.player, 'PositionComponent');
                    const entitiesHere2 = getEntitiesAtLocation(playerPosition2.location);
                    
                    for (const entityId of entitiesHere2) {
                        const name = gameState.ecs.getComponent(entityId, 'NameComponent');
                        const health = gameState.ecs.getComponent(entityId, 'HealthComponent');
                        
                        if (name && health && name.name.toLowerCase().includes(targetName.toLowerCase()) && entityId !== gameState.player) {
                            foundTarget = true;
                            gameState.fight(entityId);
                            break;
                        }
                    }
                    
                    if (!foundTarget) {
                        gameLog(`这里没有叫"${targetName}"的目标。`);
                    }
                    break;
                
                case 'use':
                case '使用':
                    if (commandParts.length < 2) {
                        gameLog("请指定要使用的物品名称。");
                        break;
                    }
                    
                    const itemName = commandParts.slice(1).join(' ');
                    let foundItem = false;
                    
                    const inventory = gameState.ecs.getComponent(gameState.player, 'InventoryComponent');
                    
                    for (const [itemId, amount] of Object.entries(inventory.items)) {
                        if (getItemName(itemId).toLowerCase().includes(itemName.toLowerCase())) {
                            foundItem = true;
                            gameState.useItem(itemId);
                            break;
                        }
                    }
                    
                    if (!foundItem) {
                        gameLog(`你没有叫"${itemName}"的物品。`);
                    }
                    break;
                
                case 'craft':
                case '合成':
                    if (commandParts.length < 2) {
                        gameLog("请指定要合成的物品名称。");
                        break;
                    }
                    
                    const recipeName = commandParts.slice(1).join(' ');
                    let foundRecipe = false;
                    
                    if (gameState.ecs.components['RecipeComponent']) {
                        for (const [entityId, recipe] of Object.entries(gameState.ecs.components['RecipeComponent'])) {
                            const name = gameState.ecs.getComponent(entityId, 'NameComponent');
                            
                            if (name && name.name.toLowerCase().includes(recipeName.toLowerCase())) {
                                foundRecipe = true;
                                gameState.craft(recipe.id);
                                break;
                            }
                        }
                    }
                    
                    if (!foundRecipe) {
                        gameLog(`没有找到名为"${recipeName}"的合成配方。`);
                    }
                    break;
                
                case 'build':
                case '建造':
                    if (commandParts.length < 2) {
                        gameLog("请指定要建造的建筑名称。");
                        break;
                    }
                    
                    const buildingName = commandParts.slice(1).join(' ');
                    let foundBuilding = false;
                    
                    if (gameState.ecs.components['BuildingComponent']) {
                        for (const [entityId, building] of Object.entries(gameState.ecs.components['BuildingComponent'])) {
                            if (!building.completed) {
                                const name = gameState.ecs.getComponent(entityId, 'NameComponent');
                                
                                if (name && name.name.toLowerCase().includes(buildingName.toLowerCase())) {
                                    foundBuilding = true;
                                    gameState.build(building.type);
                                    break;
                                }
                            }
                        }
                    }
                    
                    if (!foundBuilding) {
                        gameLog(`没有找到名为"${buildingName}"的可建造建筑。`);
                    }
                    break;
                
                case 'tasks':
                case '任务':
                    document.querySelectorAll('.menu-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    document.querySelector('.menu-item[data-panel="tasks"]').classList.add('active');
                    
                    document.querySelectorAll('.panel').forEach(panel => {
                        panel.classList.remove('active');
                    });
                    document.getElementById('tasks-panel').classList.add('active');
                    break;
                
                case 'inventory':
                case '背包':
                    document.querySelectorAll('.menu-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    document.querySelector('.menu-item[data-panel="inventory"]').classList.add('active');
                    
                    document.querySelectorAll('.panel').forEach(panel => {
                        panel.classList.remove('active');
                    });
                    document.getElementById('inventory-panel').classList.add('active');
                    break;
                
                case 'status':
                case '状态':
                    document.querySelectorAll('.menu-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    document.querySelector('.menu-item[data-panel="character"]').classList.add('active');
                    
                    document.querySelectorAll('.panel').forEach(panel => {
                        panel.classList.remove('active');
                    });
                    document.getElementById('character-panel').classList.add('active');
                    break;
                
                case 'save':
                case '保存':
                    if (gameState.saveGame()) {
                        gameLog("游戏已保存。");
                    } else {
                        gameLog("保存游戏失败。");
                    }
                    break;
                
                case 'load':
                case '加载':
                    if (gameState.loadGame()) {
                        gameLog("游戏已加载。");
                        
                        // 更新UI
                        updateCharacterInfo();
                        updateStatusBars();
                        updateInventory();
                        updateRecipes();
                        updateBuildings();
                        updateTasks();
                        updateMap();
                        
                        describeLocation(gameState.currentLocation);
                    } else {
                        gameLog("没有找到存档或加载失败。");
                    }
                    break;
                
                case 'create':
                case '创造':
                    gameState.creatorMode = true;
                    gameLog("已进入创造者模式，可以使用特殊命令。");
                    document.querySelectorAll('.menu-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    document.querySelector('.menu-item[data-panel="creator"]').classList.add('active');
                    
                    document.querySelectorAll('.panel').forEach(panel => {
                        panel.classList.remove('active');
                    });
                    document.getElementById('creator-panel').classList.add('active');
                    break;
                
                case 'exit':
                case '退出':
                    if (gameState.creatorMode) {
                        gameState.creatorMode = false;
                        gameLog("已退出创造者模式。");
                    } else {
                        gameLog("你不在创造者模式中。");
                    }
                    break;
                
                default:
                    gameLog(`未知命令: ${command}`);
                    gameLog("输入'help'或'帮助'查看可用命令。");
            }
        }

        function executeCreatorCommand() {
            if (!gameState.creatorMode) {
                gameLog("请先进入创造者模式。输入'create'或'创造'进入。");
                return;
            }
            
            const commandInput = document.getElementById('creator-command');
            const command = commandInput.value.trim();
            
            if (command === '') return;
            
            gameLog(`[创造者] > ${command}`);
            commandInput.value = '';
            
            const commandParts = command.split(' ');
            const action = commandParts[0].toLowerCase();
            
            switch (action) {
                case 'add_item':
                    // 格式: add_item [物品ID] [数量]
                    if (commandParts.length < 3) {
                        gameLog("格式错误: add_item [物品ID] [数量]");
                        break;
                    }
                    
                    const itemId = commandParts[1];
                    const amount = parseInt(commandParts[2]);
                    
                    if (isNaN(amount) || amount <= 0) {
                        gameLog("数量必须是正整数。");
                        break;
                    }
                    
                    const inventory = gameState.ecs.getComponent(gameState.player, 'InventoryComponent');
                    inventory.addItem(itemId, amount);
                    gameLog(`已添加 ${amount} 个 ${getItemName(itemId)} 到物品栏。`);
                    updateInventory();
                    break;
                
                case 'set_stat':
                    // 格式: set_stat [属性名] [值]
                    if (commandParts.length < 3) {
                        gameLog("格式错误: set_stat [属性名] [值]");
                        break;
                    }
                    
                    const statName = commandParts[1].toLowerCase();
                    const statValue = parseFloat(commandParts[2]);
                    
                    if (isNaN(statValue)) {
                        gameLog("值必须是数字。");
                        break;
                    }
                    
                    let statUpdated = false;
                    
                    switch (statName) {
                        case 'health':
                            const health = gameState.ecs.getComponent(gameState.player, 'HealthComponent');
                            health.current = Math.min(statValue, health.max);
                            statUpdated = true;
                            break;
                        case 'max_health':
                            const health2 = gameState.ecs.getComponent(gameState.player, 'HealthComponent');
                            health2.max = statValue;
                            health2.current = Math.min(health2.current, statValue);
                            statUpdated = true;
                            break;
                        case 'hunger':
                            const hunger = gameState.ecs.getComponent(gameState.player, 'HungerComponent');
                            hunger.current = Math.min(statValue, hunger.max);
                            statUpdated = true;
                            break;
                        case 'max_hunger':
                            const hunger2 = gameState.ecs.getComponent(gameState.player, 'HungerComponent');
                            hunger2.max = statValue;
                            hunger2.current = Math.min(hunger2.current, statValue);
                            statUpdated = true;
                            break;
                        case 'energy':
                            const energy = gameState.ecs.getComponent(gameState.player, 'EnergyComponent');
                            energy.current = Math.min(statValue, energy.max);
                            statUpdated = true;
                            break;
                        case 'max_energy':
                            const energy2 = gameState.ecs.getComponent(gameState.player, 'EnergyComponent');
                            energy2.max = statValue;
                            energy2.current = Math.min(energy2.current, statValue);
                            statUpdated = true;
                            break;
                        case 'strength':
                            const attributes = gameState.ecs.getComponent(gameState.player, 'AttributesComponent');
                            attributes.strength = statValue;
                            statUpdated = true;
                            break;
                        case 'agility':
                            const attributes2 = gameState.ecs.getComponent(gameState.player, 'AttributesComponent');
                            attributes2.agility = statValue;
                            statUpdated = true;
                            break;
                        case 'intelligence':
                            const attributes3 = gameState.ecs.getComponent(gameState.player, 'AttributesComponent');
                            attributes3.intelligence = statValue;
                            statUpdated = true;
                            break;
                        case 'endurance':
                            const attributes4 = gameState.ecs.getComponent(gameState.player, 'AttributesComponent');
                            attributes4.endurance = statValue;
                            statUpdated = true;
                            break;
                        case 'level':
                            const level = gameState.ecs.getComponent(gameState.player, 'LevelComponent');
                            level.level = Math.max(1, Math.floor(statValue));
                            statUpdated = true;
                            break;
                        default:
                            gameLog(`未知属性: ${statName}`);
                    }
                    
                    if (statUpdated) {
                        gameLog(`已设置 ${statName} = ${statValue}`);
                        updateStatusBars();
                        updateCharacterInfo();
                    }
                    break;
                
                case 'teleport':
                    // 格式: teleport [位置ID]
                    if (commandParts.length < 2) {
                        gameLog("格式错误: teleport [位置ID]");
                        break;
                    }
                    
                    const targetLocationId = commandParts[1];
                    let locationExists = false;
                    
                    for (const [entityId, locationComponent] of Object.entries(gameState.ecs.components['LocationComponent'])) {
                        if (locationComponent.id === targetLocationId) {
                            locationExists = true;
                            
                            // 直接传送
                            const playerPosition = gameState.ecs.getComponent(gameState.player, 'PositionComponent');
                            playerPosition.location = targetLocationId;
                            gameState.currentLocation = targetLocationId;
                            
                            gameLog(`已传送到 ${getLocationName(targetLocationId)}`);
                            describeLocation(targetLocationId);
                            updateMap();
                            break;
                        }
                    }
                    
                    if (!locationExists) {
                        gameLog(`位置ID "${targetLocationId}"不存在。`);
                    }
                    break;
                
                case 'spawn':
                    // 格式: spawn [类型] [ID] [名称]
                    if (commandParts.length < 4) {
                        gameLog("格式错误: spawn [类型] [ID] [名称]");
                        break;
                    }
                    
                    const spawnType = commandParts[1].toLowerCase();
                    const spawnId = commandParts[2];
                    const spawnName = commandParts.slice(3).join(' ');
                    
                    const currentLocation = gameState.ecs.getComponent(gameState.player, 'PositionComponent').location;
                    
                    switch (spawnType) {
                        case 'resource':
                            gameState.createResource(currentLocation, spawnId, spawnName, spawnId, 10);
                            gameLog(`已在当前位置生成资源: ${spawnName}`);
                            break;
                        case 'npc':
                            gameState.createNPC(currentLocation, spawnId, spawnName, `创建者生成的NPC: ${spawnName}`, true);
                            gameLog(`已在当前位置生成NPC: ${spawnName}`);
                            break;
                        case 'enemy':
                            gameState.createNPC(currentLocation, spawnId, spawnName, `创建者生成的敌人: ${spawnName}`, false);
                            gameLog(`已在当前位置生成敌人: ${spawnName}`);
                            break;
                        default:
                            gameLog(`未知的生成类型: ${spawnType}`);
                            gameLog("可用类型: resource, npc, enemy");
                    }
                    break;
                
                case 'help':
                    gameLog("创造者模式命令:");
                    gameLog("add_item [物品ID] [数量] - 添加物品到物品栏");
                    gameLog("set_stat [属性名] [值] - 设置角色属性");
                    gameLog("teleport [位置ID] - 传送到指定位置");
                    gameLog("spawn [类型] [ID] [名称] - 在当前位置生成实体");
                    gameLog("exit - 退出创造者模式");
                    break;
                
                default:
                    gameLog(`未知的创造者命令: ${action}`);
                    gameLog("输入'help'查看可用命令。");
            }
        }
    </script>
</body>
</html>
